from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet



from meiduo_admin.serializers.permission import PermissionSerializer, ContentTypeSerializer
from meiduo_admin.utils import PageNum, PerPermission


class PermissionView(ModelViewSet):
    serializer_class = PermissionSerializer
    queryset = Permission.objects.all()
    pagination_class = PageNum
    permission_classes = [IsAdminUser]
    permission_classes_by_action = {'create': [PerPermission],
                                    'update': [PerPermission],
                                    'destroy': [PerPermission]
                                    }

    def get_permissions(self):
        try:
            # return permission_classes depending on `action`
            return [permission() for permission in self.permission_classes_by_action[self.action]]
        except KeyError:
            # action is not set return default permission_classes
            return [permission() for permission in self.permission_classes]

    def content_types(self,request):
        instances = ContentType.objects.all()
        ser = ContentTypeSerializer(instances,many=True)
        return Response(ser.data)